package cn.huijielong.common.utils;

import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 返回数据
 * 
 * @date 2016年10月27日 下午9:59:27
 */
public class RD extends HashMap<String, Object> {
	
	public final static String DATA_KEY="DataKey";
	private static final long serialVersionUID = 1L;
	
	private Map map=null;
	
	public RD() {
		put("code", 0);
		put("msg", "success");
	}
	
	public static RD error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}
	
	public static RD error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	
	public static RD error(int code, String msg) {
		RD r = new RD();
		r.put("code", code);
		r.put("msg", msg);
		return r;
	}

	public static RD ok(String msg) {
		RD r = new RD();
		r.put("msg", msg);
		return r;
	}
	
	public static RD ok(Map<String, Object> map) {
		RD r = new RD();
		r.putAll(map);
		return r;
	}
	
	public static RD ok() {
		return new RD();
	}

	public RD put(String key, Object value) {
		super.put(key, value);
		return this;
	}
	public boolean isOk() {
		Object code=get("code");
		return code!=null && Status.SUCCESS.equals(code.toString());
	}
	/**
	 * 加入数据对象
	 * @param data
	 * @return
	 */
	public RD setData(Object data) {
		if(data instanceof Map) {
			map=(Map)data;
		}
		return setData("data",data);
	}
	public RD setData(String key,Object data) {
		if(data==null) {
			super.put(key, VSUtil.getMapper().createObjectNode());
			return this;
		}else {
			super.put(key, data);
			return this;
		}
	}
	public RD putDataValue(String k,Object v) {
		if(map==null) {
			map=new HashMap<String,Object>();
			setData(map);
		}
		map.put(k, v);
		return this;
	}
	public String getDataValue(String k) {
		Object v=map==null?null:map.get(k);
		return v==null?"":v.toString();
	}
	/**
	 * 加入数据对象数组
	 * @param data
	 * @return
	 */
	public RD setDatas(List<?> data) {
		return setDatas("data",data);
	}
	public RD setDatas(String key,List<?> data) {
		if(data==null) {
			super.put(key, VSUtil.getMapper().createArrayNode());
			return this;
		}else {
			super.put(key, data);
			return this;
		}
	}
}
